<script setup>
import { ref, onMounted, watch, onUnmounted, computed, toRefs } from 'vue'
import Chart from 'chart.js/auto'

const props = defineProps(['finishedWords', 'unfinishedWords'])
const { finishedWords, unfinishedWords } = toRefs(props)

const schedulePercent = computed(() => {
  return Math.round(
    (finishedWords.value / (finishedWords.value + unfinishedWords.value)) * 100
  )
})
const chartRef = ref(null)
const chartInstance = ref(null) // 新增图表实例引用

// 将数据转换为响应式对象
const data = ref({
  labels: [`已记忆${finishedWords.value}`, `未记忆${unfinishedWords.value}`],
  datasets: [{
    data: [finishedWords.value, unfinishedWords.value],
    backgroundColor: ['#C4FFAF', '#E8E8E8'],
    borderWidth: 0
  }]
})

// 中心文字插件
const centerText = {
  id: 'centerText',
  beforeDraw(chart) {
    const { ctx } = chart
    const text = `进度 ${schedulePercent.value}%`

    ctx.save()
    ctx.font = 'bold 24px Arial'
    ctx.fillStyle = '#4A4A4A'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(text, chart.width / 2, chart.height / 2.2)
    ctx.restore()
  }
}

// 初始化/更新图表函数
const updateChart = () => {
  if (chartInstance.value) {
    chartInstance.value.destroy() // 销毁旧实例
  }

  chartInstance.value = new Chart(chartRef.value.getContext('2d'), {
    type: 'doughnut',
    data: data.value,
    plugins: [centerText],
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            boxWidth: 10,
            padding: 20
          }
        }
      },
      cutout: '70%',
      animation: {
        duration: 0 // 添加过渡动画
      }
    }
  })
}

watch([finishedWords, unfinishedWords], ([newFinished, newUnfinished]) => {
  data.value = {
    labels: [`已记忆${newFinished}`, `未记忆${newUnfinished}`],
    datasets: [{
      data: [newFinished, newUnfinished],
      backgroundColor: ['#C4FFAF', '#E8E8E8'],
      borderWidth: 0
    }]
  }
  updateChart()
}, { deep: true })

// 初始化
onMounted(() => {
  console.log('finishedWords:', finishedWords);

  updateChart()
})

// 清理
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.destroy()
  }
})
</script>

<template>
  <div class="chart-container">
    <canvas ref="chartRef"></canvas>
  </div>
</template>

<style scoped>
.chart-container {
  width: 250px;
  height: 250px;
  position: relative;
}
</style>
